package fragments;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseFragment;
import com.example.administrator.newxlmedical.R;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import adapters.UserRightsAdapter;
import beans.NewUserInfoBean;
import beans.PutAndDeleteBean;
import beans.ResponeSupplierRightsBean;
import beans.ResultSupplierRightsBean;
import beans.UserInfoBean;
import beans.UserRightsBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import constants.Constants;
import constants.HandlerConstant;
import dialogs.UserRightsDialog;
import dialogs.UserRightsSupplierDialog;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import utils.ActivityUtil;
import utils.FormateUtils;
import utils.ObjectSaveUtil;
import utils.TimeUtil;
import utils.ToastUtil;
import utils.UserRightSortUtils;
import utils.ViewUtil;

/**
 * A simple {@link Fragment} subclass.
 */
public class UserRightsFragment extends BaseFragment implements UserRightsAdapter.OnClickListener {

    @BindView(R.id.rv_user_rights)
    RecyclerView recyclerView;
    @BindView(R.id.fl_user_rights_empty)
    FrameLayout flEmpty;

    Unbinder unbinder;
    @BindView(R.id.tv_user_rights_id)
    TextView tvUserRightsId;
    @BindView(R.id.iv_user_rights_id)
    ImageView ivUserRightsId;
    @BindView(R.id.tv_user_rights_name)
    TextView tvUserRightsName;
    @BindView(R.id.iv_user_rights_name)
    ImageView ivUserRightsName;
    @BindView(R.id.rl_user_rights_id)
    RelativeLayout rlUserRightsId;
    @BindView(R.id.rl_user_rights_name)
    RelativeLayout rlUserRightsName;
    private UserRightsAdapter adapter;
    private List<UserRightsBean> list = new ArrayList<>();
    private List<UserRightsBean> nomalList = new ArrayList<>();
    private String[] roleType;
    private Map<Integer, String> hashMap = new HashMap<>();
    private StringBuilder sbCabinetInfoIds = new StringBuilder();
    private String cabinetInfoIds = "";
    //(拼接医药厂商可用的CabinetInfoId)
    private StringBuilder sbEnableLogicNumber = new StringBuilder();
    private int netWorkCount;
    private UserRightsSupplierDialog supplierDialog;
    private UserRightsDialog userRightsDialog;
    private boolean isFrist = true;
    private NewUserInfoBean.DataBean userInfoBean;
    private long starTime;
    private int lastLoadDataItemPosition;
    private boolean isSortName, isSortId;
    private int sortName, sortId;

    public UserRightsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_user_rights, container, false);
        }
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        userInfoBean = (NewUserInfoBean.DataBean) ObjectSaveUtil.readObject(mContext, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);
        Map<Integer, String> map = (Map<Integer, String>) ObjectSaveUtil.readObject(mContext, Constants.CABINETINFO_LOGICNUMBER_HASHMAP, Constants.CABINETINFO_LOGICNUMBER_HASHMAP);
        if (map != null) {
            hashMap = map;
        }

        Iterator iter = hashMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            sbCabinetInfoIds.append(entry.getKey() + ",");
        }

        if (sbCabinetInfoIds.length() > 0) {
            cabinetInfoIds = sbCabinetInfoIds.deleteCharAt(sbCabinetInfoIds.length() - 1).toString();
        }

        roleType = FormateUtils.getRoleType();
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        adapter = new UserRightsAdapter(mContext, list, userInfoBean);
        adapter.setOnClickListener(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        getUserInfo();
    }

    private void getUserInfo() {
        list.clear();
        nomalList.clear();
        hideEmptyView();
        showLoadingView(flEmpty);
        String sql = "select * from UserInfo where (LeftImg is not null or FingerprintId > 0) and DelFlag = 0 and RoleInfoId !=5";
        starTime = System.currentTimeMillis();
        if (userInfoBean.getRoleInfoId() != 5) {
            sql = "select Name,Ucode,ID,Enable,RoleInfoId,WorkKind,Department,SubTime from UserInfo where (LeftImg is not null or FingerprintId is not null) and DelFlag = 0 and RoleInfoId !=5";
        } else {
            sql = "select Name,Ucode,ID,Enable,RoleInfoId,WorkKind,Department,SubTime from UserInfo where (LeftImg is not null or FingerprintId is not null) and DelFlag = 0 ";
        }
        GetRetrofit.getInstance().getUserInfo(NetAddress.token, NetAddress.machineCode, sql)
                .enqueue(new Callback<ArrayList<UserInfoBean>>() {
                    @Override
                    public void onResponse(Call<ArrayList<UserInfoBean>> call, Response<ArrayList<UserInfoBean>> response) {
                        ArrayList<UserInfoBean> body = response.body();
                        StringBuilder stringBuilder = new StringBuilder();
                        hideLoadingView();
                        long endTime = System.currentTimeMillis();
                        Log.e(TAG, "onResponse: " + (endTime - starTime));
                        if (body != null && body.size() > 0) {
                            for (int i = 0; i < body.size(); i++) {
                                UserInfoBean userInfoBean = body.get(i);
                                UserRightsBean bean = new UserRightsBean();
                                bean.setName(userInfoBean.getName());
                                bean.setNumber(userInfoBean.getUCode());
                                bean.setUserInfoId(userInfoBean.getID());
                                bean.setEnable(userInfoBean.isEnable());
                                bean.setWorkType(userInfoBean.getWorkKind());
                                int roleInfoId = userInfoBean.getRoleInfoId();
                                if (roleInfoId > 0) {
                                    bean.setRoleInfoId(roleInfoId);
                                    if (roleInfoId <= roleType.length) {
                                        bean.setRole(roleType[roleInfoId - 1]);
                                    }
                                } else {
                                    bean.setRole("手持机");
                                }
                                bean.setDepartment(userInfoBean.getDepartment());
                                bean.setTime(TimeUtil.getTimeOnDate(userInfoBean.getSubTime()));
                                stringBuilder.append("'" + roleInfoId + "',");
                                list.add(bean);
                                nomalList.add(bean);
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            if (list.size() == 0) {
                                showEmptyView(flEmpty);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ArrayList<UserInfoBean>> call, Throwable t) {
                        if (flEmpty != null) {
                            showEmptyView(flEmpty);
                            hideLoadingView();
                        }
                        long endTime = System.currentTimeMillis();
                        Log.e(TAG, "onFailure: " + (endTime - starTime) + "  " + t.getMessage());
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onChangeClickListener(int position) {
        UserRightsBean userRightsBean = list.get(position);
        if (userRightsBean.getRoleInfoId() == 4) {
            new UserRightsSupplierDialog(mContext, R.style.dialog, userRightsBean, new UserRightsSupplierDialog.OnClickListener() {
                @Override
                public void onChangeClickListener(String name, String enable, ResultSupplierRightsBean bean, UserRightsSupplierDialog dialog) {
                    supplierDialog = dialog;
//                    putUserInfo("set Enable = '" + enable + "' where Name = '" + name + "'", 2);
                    changeAuth(bean);
                }
            }).show();
        } else {

            new UserRightsDialog(mContext, R.style.dialog, userRightsBean, new UserRightsDialog.OnClickListener() {
                @Override
                public void onChangeClickListener(int roleInfoId, String name, UserRightsDialog dialog) {
                    userRightsDialog = dialog;
                    putUserInfo("set RoleInfoId = " + roleInfoId + " where Name = '" + name + "'", 1);
                }
            }).show();
        }
    }

    //type    1代表其他,2代表供应商
    private void putUserInfo(String sql, final int type) {
        Call<PutAndDeleteBean> call = GetRetrofit.getInstance().putUserInfo(NetAddress.token, NetAddress.machineCode, sql);
        call.enqueue(new Callback<PutAndDeleteBean>() {
            @Override
            public void onResponse(Call<PutAndDeleteBean> call, Response<PutAndDeleteBean> response) {
                PutAndDeleteBean body = response.body();
                if (type == 2) {
                    sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                } else {
                    ToastUtil.showToast(mContext, "修改成功");
                    userRightsDialog.dismiss();
                    sendEmptyMessage(HandlerConstant.REFRESH_NET);
                }
            }

            @Override
            public void onFailure(Call<PutAndDeleteBean> call, Throwable t) {

            }
        });
    }

    private void changeAuth(ResultSupplierRightsBean bean) {
        GetRetrofit.getInstance().setSupplierRights(NetAddress.token, NetAddress.machineCode, bean).subscribeOn(Schedulers.io()).subscribe(new Action1<ResponeSupplierRightsBean>() {
            @Override
            public void call(ResponeSupplierRightsBean responeSupplierRightsBean) {
                //不管有没有增加或减少的权限,请求接口成功就会返回ok
                if ("ok".equals(responeSupplierRightsBean.getResult())) {
                    Log.e("CCC", "call: ok");
                    sbEnableLogicNumber.delete(0, sbEnableLogicNumber.length());
                    List<ResponeSupplierRightsBean.CurrentBean> currentBeanList = responeSupplierRightsBean.getCurrent();
                    for (int i = 0; i < currentBeanList.size(); i++) {
                        if (cabinetInfoIds.contains(String.valueOf(currentBeanList.get(i).getCabinetInfoId()))) {
                            if (!sbEnableLogicNumber.toString().contains(hashMap.get(currentBeanList.get(i).getCabinetInfoId()))) {
                                sbEnableLogicNumber.append(hashMap.get(currentBeanList.get(i).getCabinetInfoId()) + ",");
                            }
                        }
                    }

                    Log.e("CCC", "call: " + sbCabinetInfoIds.toString());
                    Log.e("CCC", "call: " + sbEnableLogicNumber.toString());

                    SharedPreferences.Editor edit = ActivityUtil.getSharedPreferences(mContext).edit();
                    edit.putString(Constants.ENABLE_LOGICNUMBER, sbEnableLogicNumber.toString());
                    edit.commit();
                    sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                    sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                }
            }
        }, new MyAction1());

    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case HandlerConstant.FINISH_NETWORK:
                netWorkCount++;
                if (netWorkCount == 2) {
                    netWorkCount = 0;
                    ToastUtil.showToast(mContext, "修改成功");
                    supplierDialog.dismiss();
                    sendEmptyMessage(HandlerConstant.REFRESH_NET);
                }
                break;
            case HandlerConstant.REFRESH_NET:
                list.clear();
                getUserInfo();
                break;
            case HandlerConstant.REFRESH:
                list.clear();
                getUserInfo();
                break;
        }
    }

    @OnClick({R.id.rl_user_rights_id, R.id.rl_user_rights_name})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_user_rights_id:
                sort(2);

                break;
            case R.id.rl_user_rights_name:
//                Log.e(TAG, "onViewClicked: ");
                sort(1);
                break;
        }
    }

    private void sort(int type) {
        if (type == 1) { // 按物品名排序
            if (sortName != 2) {
                sortName++;
                isSortName = !isSortName;
                UserRightSortUtils.sortUserRightName(list, isSortName);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(nomalList);
            }
        } else {
            sortName = 0;
            isSortName = false;
        }
        if (type == 2) {
            if (sortId != 2) {
                sortId++;
                isSortId = !isSortId;
                UserRightSortUtils.sortUserRightId(list, isSortId);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(nomalList);
            }
        } else {
            sortId = 0;
            isSortId = false;
        }

        ViewUtil.setSortColor(mContext, tvUserRightsName, ivUserRightsName, sortName);
        ViewUtil.setSortColor(mContext, tvUserRightsId, ivUserRightsId, sortId);
        adapter.notifyDataSetChanged();
    }

    private void clearSortDate() {
        sortName = 0;
        sortId = 0;
    }
}